
import 'dart:io';
import 'package:intl/intl.dart';
import 'package:path_provider/path_provider.dart';
import 'package:synchronized/synchronized.dart';

class FileSave{

  void saveFile(Lock lock, String notes) async{
    if(Platform.isAndroid){
      // 获取应用文档目录并创建文件
      Directory? documentsDir = await getExternalStorageDirectory();
      String documentsPath = documentsDir!.path;
      String dateTime= DateFormat("yyyy_MM_dd").format(DateTime.now());
      File file = File('$documentsPath/log_'+dateTime + ".txt");
      if(!file.existsSync()) {
        file.createSync();
      }
      writeToFile(lock,file, notes);
    }
    if(Platform.isIOS){
      Directory? dir;
      dir = await getTemporaryDirectory();
      String sDCardDir = dir!.path;
      sDCardDir= sDCardDir.replaceFirst("Library/Caches", "Documents");
      String dateTime= DateFormat("yyyy_MM_dd").format(DateTime.now());
      // var savePath = sDCardDir + "/report/log_"+dateTime + ".log";
      File file = File(sDCardDir + "/log");
      if (!await file.exists()) {
        Directory(sDCardDir + "/log").createSync();
      }
      File f = File(sDCardDir + "/log/log_"+dateTime + ".log");
      if (!await f.exists()) {
        f.createSync();
      }
      writeToFile(lock,f, notes);
    }
  }

//将数据内容写入指定文件中
  void writeToFile(Lock lock, File file, String notes) async {
    print(notes);
    await lock.synchronized(() async {
      File file1 = await file.writeAsString(notes+"\n",mode: FileMode.append);
      if(file1.existsSync()) {

      }
    });
  }
}